<template>
  <div class="img-dropdown-select">
    <el-popover
      placement="bottom-start"
      trigger="click"
      :teleported="false"
      :width="158"
      ref="popover"
    >
      <div class="img-list">
        <div class="item"
          :style="{ width: `calc(100% / ${col})` }"
          v-for="item in imgList"
          :key="item.value"
          @click="handleUpdateData(item.value)">
          <img :src="item.img" alt="">
        </div>
      </div>
      <template #reference>
        <div class="img-dropdown-select-btn">
          <div class="select-img">
            <img :src="selectImg" alt="">
          </div>
          <i class="ri-arrow-down-s-line"></i>
        </div>
      </template>
    </el-popover>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
const emits = defineEmits(['update:modelValue', 'change'])

const props = defineProps({
  imgList: {
    type: Array,
    default: () => []
  },
  col: {
    type: Number,
    default: 3
  },
  modelValue: [String, Number]
})

const popover = ref()

const selectImg = computed(() => {
  return props.imgList.find(o => o.value === props.modelValue)?.img
})

function handleUpdateData (value) {
  if (value !== props.modelValue) {
    emits('change', value)
  }
  emits('update:modelValue', value)
  popover.value.hide()
}
</script>

<style lang="scss" scoped>
.img-dropdown-select {
  &-btn {
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0.03);
    box-shadow: 0px 0px 1.5px rgba(0, 0, 0, 0.2);
    display: flex;
    justify-content: space-between;
    padding: 2px 4px 2px 8px;
    align-items: center;
    .select-img {
      font-size: 0;
      img {
        height: 22px;
      }
    }
    .ri-arrow-down-s-line {
      color: #000;
      font-size: 16px;
      margin-left: 10px;
      font-weight: normal;
    }
  }
  .img-list {
    display: flex;
    flex-wrap: wrap;
    .item {
      font-size: 0;
      padding: 4px 10px;
      border-radius: 4px;
      margin: 4px 0;
      img {
        width: 100%;
      }
      &:hover {
        background-color: rgba(0, 0, 0, 0.03);
      }
    }
  }
}
</style>
